package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    //0 0/2 * * * ?
    //每2分钟执行一次
    @Scheduled(cron = "0 0/2 * * * ?")
    public void processTimeOuter(){
        log.info("定时任务检查待支付订单信息...");
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTime = now.plusMinutes(-15); // 15分钟前
        List<Orders> orders = orderMapper.selectByTimeOut(Orders.PENDING_PAYMENT,localDateTime);
        if(orders!=null && orders.size()>0){
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时未支付，已自动取消");
                order.setCancelTime(now);
                orderMapper.update(order);
            }
        }
    }
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliver(){
        log.info("定时任务检查派送情况信息...");
        List<Orders> orders = orderMapper.selectByTimeOut(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now());
        if(orders!=null && orders.size()>0){
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }

    }
}
